<template>
  <el-row>
    <el-col :span="24">
      <div class="box">
        <div>
          <div class="box-header">
            <h3 class="box-title" style="line-height: 40px;float: left;">辅导员信息导入</h3>
            <el-upload
              style="display: inline; margin-left: 10px;margin-right: 10px;"
              action="#"
              ref="fileupload"
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              :show-file-list="false"
              :http-request="upLoadChange"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">上传文件<i class="el-icon-upload2 el-icon--right"></i></el-button>
            </el-upload>
            <el-button size="small" type="primary" class="header-button" @click="showExportModel()">
              <i class="el-icon-download el-icon--right">
                下载模板
                <!-- <a href='http://localhost/cultivate/php/uploads/demo.xlsx' download>下载模板</a> -->
              </i>         
            </el-button>
            <el-button size="small" type="success" class="header-button" @click="comfirmUpload()" v-if="tableData.length">
              <i class="el-icon-s-promotion el-icon--right">
                确认上传
              </i>         
            </el-button>
            <el-button v-if="showError" size="small" type="info" icon="el-icon-error el-icon--right" @click="exportExcel">导出失败信息</el-button>
            <el-button size="small" type="primary" class="header-button" @click="dialogVisible = true">
                重置辅导员密码
                <!-- <a href='http://localhost/cultivate/php/uploads/demo.xlsx' download>下载模板</a> -->
              </el-button> 
          </div>
        <el-dialog 
        title="重置辅导员密码" 
        :visible.sync="dialogVisible"
        width="30%"
        center>
          <el-form :model="form">
            <el-form-item label="账号" :label-width="formLabelWidth">
              <el-input v-model="form.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
              <el-input v-model="form.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" :label-width="formLabelWidth">
              <el-input v-model="form.repassword" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="comfirmpassword(form)">确 定</el-button>
          </div>
        </el-dialog>
          <div class="box-body">
            <!-- @cell-cl<el-dialog
  title="提示"
  :visible.sync="dialogVisible"
  width="30%"
  :before-close="handleClose">
  <span>这是一段信息</span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
</el-dialog>ck="editCell" -->       
            <el-table
              :data="tableData"
              ref="multipleTable"
              border
              :row-style="tableRowStatus">
              <el-table-column  type="index" label="#" width="50"></el-table-column>
              <el-table-column  prop="level_1" label="工作部门" width="80"></el-table-column>
              <el-table-column  prop="level_2" label="工作身份" width="80"></el-table-column>
              <el-table-column  prop="name" label="姓名" width="80"></el-table-column>
              <el-table-column  prop="idnumber" label="身份证号" width="180"></el-table-column>
              <el-table-column  prop="sex" label="性别" width="50"></el-table-column>
              <el-table-column  prop="nation" label="民族" width="80"></el-table-column>
              <el-table-column  prop="birth" label="出生年月" width="100"></el-table-column>
              <el-table-column  prop="edu" label="学历" width="80"></el-table-column>
              <el-table-column  prop="degree" label="学位" width="80"></el-table-column>
              <el-table-column  prop="politics" label="政治面貌" width="80"></el-table-column>
              <el-table-column  prop="preoccupation" label="现任职务名称" width="110"></el-table-column>
              <el-table-column  prop="majoroccupation" label="专业技术职务名称" width="140"></el-table-column>
              <el-table-column  prop="majortime" label="参加工作时间" width="110"></el-table-column>
              <el-table-column  prop="sch" :formatter="showSchName" label="学校" width="140"></el-table-column>
              <el-table-column  prop="jobrank" label="职务级别" width="80"></el-table-column>
              <el-table-column  prop="address" label="通讯地址" width="150"></el-table-column>
              <el-table-column  prop="postalcode" label="邮政编码" width="80"></el-table-column>
              <el-table-column  prop="office" label="办公电话" width="120"></el-table-column>
              <el-table-column  prop="phone" label="手机" width="120"></el-table-column>
              <el-table-column  prop="qq" label="QQ号" width="100"></el-table-column>
              <el-table-column  prop="fax" label="传真" width="120"></el-table-column>
              <el-table-column  prop="email" label="电子邮箱" width="160"></el-table-column>
              <!-- <el-table-column  v-if="tableData.length > 0 && 'error' in tableData[0]" prop="error" label="失败原因" width="200" fixed="right"></el-table-column> -->
              <el-table-column  v-if="showError" prop="error" label="失败原因" width="200" fixed="right"></el-table-column>
              <el-table-column label="操作"  width="50" fixed="right">
                <template slot-scope="scope">
                  <el-button 
                    size="mini"
                    type="danger" 
                    icon="el-icon-delete"
                    @click.stop="Delete(scope)" 
                    circle></el-button>
                  </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import http from './../../../assets/js/http'
import XLSX from 'xlsx'
import moment from 'moment'
export default {
  data () {
    return {
      prop: {
        'level_1': '工作部门',
        'level_2': '工作身份',
        'name': '姓名',
        'idnumber': '身份证号',
        'sex': '性别',
        'nation': '民族',
        'birth': '出生年月',
        'edu': '学历',
        'degree': '学位',
        'politics': '政治面貌',
        'preoccupation': '现任职务名称',
        'majoroccupation': '专业技术职务名称',
        'majortime': '参加工作时间',
        // 'sch': '学校',
        'jobrank': '职务级别',
        'address': '通讯地址',
        'postalcode': '邮政编码',
        'office': '办公电话',
        'phone': '手机',
        'qq': 'QQ号',
        'fax': '传真',
        'email': '电子邮箱'
      },
      importUrl: window.HOST + '/admin/upload/index',
      tableData: [],
      dialogVisible: false,
      form:{
        username: '',
        password: '',
        repassword: ''
      },
      sch:Lockr.get('userInfo').sch, 
      notNullregs: [
        {
          'name': 'name',
          'reg': ['notnull', 'info']
        },
        {
          'name': 'idnumber',
          'reg': ['notnull', 'idnumber']
        }],
      notNullregsTips: {
        'nameTips': '姓名',
        'idnumberTips': '身份证号',
        'sexTips': '性别',
        'nationTips': '民族',
        'birthTips': '出生年月',
        'eduTips': '学历',
        'degreeTips': '学位',
        'politicsTips': '政治面貌',
        'preoccupationTips': '现任职务名称',
        'majoroccupationTips': '专业技术职务名称',
        'majortimeTips': '参加工作时间',
        // 'schTips': '学校',
        'jobrankTips': '职务级别',
        'addressTips': '通讯地址',
        'postalcodeTips': '邮政编码',
        'officeTips': '办公电话',
        'phoneTips': '手机',
        'qqTips': 'QQ号',
        'faxTips': '传真',
        'emailTips': '电子邮箱'
      },
      tips: {
         'usernameTips': '账号',
        'passwordTips': '密码',
        'repasswordTips': '确认密码'
      },
      
      nullRegs: {
        'sex': function(e) {
          return e == '男' || e == '女'
        },
        // 'nation': function(e) {
        //   return e == '汉族' || e == '少数民族'
        // },
        // 'birth': function(e) {
        //   return /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/.test(e)
        //   },
        'edu': function(e) {
          return ['博士研究生', '硕士研究生', '大学本科', '大学专科', '高中', '其他'].some(function(item) {
            return item == e
          })
        },
        'degree': function(e) {
          return ['博士', '硕士', '学士', '其他'].some(function(item) {
            return item == e
          })
        },
        'politics': function(e) {
          return ['中共党员', '中共预备党员', '共青团员', '群众', '民革党员', '民盟盟员', '民建会员', '民进会员', '农工党党员', '致公党党员', '九三学社社员', '台盟盟员', '无党派人士', '其他'].some(function(item) {
            return item == e
          })
        },
        'majortime': function(e) {
          return /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/.test(e)
        },
        /* 'sch': function(e) {
          return true
        }, */
        'postalcode': function(e) {
          return /^[1-9]\d{5}(?!\d)$/.test(e)
        },
        'office': function(e) {
          return /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/.test(e)
        },
        'phone': function(e) {
          return /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(e)
        },
        'qq': function(e) {
          return /^[0-9]{5,12}$/.test(e)
        },
        'fax': function(e) {
          return /^(\d{3,4}-)?\d{7,8}$/.test(e)
        },
        'email': function(e) {
          return /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/.test(e)
        }
      },
      showError: false,
      userInfo: Lockr.get("userInfo")
    }
  },
  created() {
    _g.closeGlobalLoading()
  },
  methods: {
    comfirmpassword(form) {
      // console.log(this.sch)
      var checkResult = this.checkList(form, [
        {
          name: 'username',
          reg: ['notnull']
        },
        {
          name: 'password',
          reg: ['notnull']
        },
        {
          name: 'repassword',
          reg: ['notnull']
        }
      ])
      // console.log(checkResult)
      if (_g.j2s(checkResult) === '{}') { 
        let data = {
          sch: this.sch,
          username: this.form.username,
          password: this.form.password,
          repassword: this.form.repassword
        }
        // console.log(data)
        this.apiPost('admin/Train/repassword',data).then((res) =>{
          this.handelResponse(res,(data) =>{
            // console.log(res)
            _g.toastMsg('success',res.data)
            this.dialogVisible = false
            this.form = {}
          })
        })
      }else {
        for (const key in checkResult) {
            _g.toastMsg('error', this.tips[key] + checkResult[key])
            break
          }
        }
    },
    showSchName(row) {
      return Lockr.get('schInfo')['sch_id_' + row.sch]['sch_name']
    },
    check(data, error, successList) {
      let _this = this
      data.forEach((element, index) => {
        // 先校验IdNumber和name
        let checkResult = _this.checkList(element, _this.notNullregs)
        if (_g.j2s(checkResult) != '{}') {
          for (const key in checkResult) {
            error.push({
              msg: _this.notNullregsTips[key] + checkResult[key],
              index: index
            })
            break
          }
        } else {
          // 在校验可以空的字段
          let success = true
          for (var key in _this.nullRegs) {
            if (element[key] != null && !_this.nullRegs[key](element[key])) {
              success = false
              error.push({
                msg: '【 ' + _this.prop[key] + ' 】格式错误',
                index: index
              })
              break
            }
          }
          if (success) {
            element['index'] = index
            successList.push(element)
          }
        }
      })
    },
    comfirmUpload () {
      let data = this.tableData
      // 做校验
      let _this = this
      let error = []
      let successList = []
      _this.check(data, error, successList)
      if (successList.length > 0) {
        // 0. if 如果前端有通过校验的数据
        let tem = {
          successList: successList,
          sch_level_1: this.userInfo.level_1
        }
        console.log(tem)
        this.apiPost('admin/Train/TrainImport', tem).then((res) => {
          this.handelResponse(res, (data) => {
            // console.log(res)
            if (data.isSuccess) {
              // 1. if 前端通过校验并且后端没有重复
              _g.toastMsg('success', '信息导入成功')
              if (error.length > 0) {
                // 2. if 当前的tableData = 未通过前端校验的数据
                let temp = []
                error.forEach(element => {
                  _this.tableData[element.index]['error'] = element.msg
                  temp.push(_this.tableData[element.index])
                })
                _this.tableData = temp
                _this.showError = true
                setTimeout(() => {
                  _g.toastMsg('error', '【 # ' + (error[0]['index'] + 1) + ' 】' + error[0]['msg'])
                }, 1000);
              } else {
                // 2. else 数据前后端都通过校验，并且全部导入成功
                _this.tableData = []
              }
            } else {
              // 1. else 前端校验通过，但是身份证在后端重复，就将这些数据放入error中，再通过索引index，从tabelData中取出错误的数据
              // console.log(data.errorList)
              data.errorList.forEach((element, index) => {
                error.push({
                  msg: element.msg,
                  index: element.index
                })
              })
              // console.log(error)
              let temp = []
              error.sort((a, b) => a.index - b.index)
              error.forEach(element => {
                _this.tableData[element.index]['error'] = element.msg
                temp.push(_this.tableData[element.index])
              })
              console.log(_this.tableData)
              _this.tableData = temp
              _this.showError = true
              _g.toastMsg('error', '【 # ' + (error[0]['index'] + 1) + ' 】' + error[0]['msg'])
            }
          })
        })
      } else {
        // 0. else 前端数据全部校验失败
        let temp = []
        error.forEach(element => {
          _this.tableData[element.index]['error'] = element.msg
          temp.push(_this.tableData[element.index])
        })
        _this.tableData = temp
        _this.showError = true
        _g.toastMsg('error', '【 # ' + (error[0]['index'] + 1) + ' 】' + error[0]['msg'])
      }
    },
    Delete (row) {
      // 点击的第几个delete按钮（row.$index）,就删除this.tableData中的数组
      this.tableData.forEach((element, index) => {
        if(index === row.$index) {
          this.tableData.splice(row.$index,1)
          if (this.tableData.length === 0 ) {
            this.showError =false
          }
        }
      })
    },
    // 导出模板
    showExportModel () {
      // window.location.href="http://localhost/cultivate/php/uploads/demo.xlsx";
      this.apiPost('admin/Download/DownloadTemplate').then((res) => {
        this.handelResponse(res, (data) => {
          window.location.href = res.data.file_dir
        })
      })
    },
    // 导出失败表
    exportExcel() {
      var _that = this
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../../excel/export2Excel') //路径根据实际路径进行修改
        const tHeader = ['工作部门','工作身份','姓名','身份证号','性别','民族','出生年月','学历','学位','政治面貌','现任职务名称','专业技术职务名称','参加工作时间','学校','职务级别','通讯地址','邮政编码','办公电话','手机','QQ号','传真','电子邮箱','失败原因']
        // 导出的表头字段名，其实就是对应table的prop名字
        const filterVal = ['level_1','level_2','name','idnumber','sex','nation','birth','edu','degree','politics','preoccupation','majoroccupation','majortime','sch_name','jobrank','address','postalcode','office','phone','qq','fax','email','error']
        const list = _that.tableData;
        list.forEach(element => {
          /* 
            由于宣传部老师导入的时候，学校是根据宣传部老师的sch进行导入的。
            所以错误信息导出的时候，学校将会显示的是宣传部老师的学校id。
            因此需要将每个错误的信息中的sch_id换成sch_name导出
          */
          element.sch_name = Lockr.get('schInfo')['sch_id_' + element.sch]['sch_name']
        });
        const data = _that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '信息导入失败表');// 导出的表格名称，根据需要自己命名
      })
    },
    formatJson(filterVal, jsonData) {
        console.log(jsonData)
        return jsonData.map(v => filterVal.map(j => v[j]))
    },
    upLoadChange (content) {
      this.$message.success('文件解析成功，数据如下表')
    },
    beforeUpload (file) {
      var reader = new FileReader()
      var _this = this
      reader.onload = function(e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {type: 'binary'});
        var result = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        // 方法1
        _this.getList(result)
        console.log(result)

        // 方法2
        // excel 数据再处理
        /* let arr = []
        result.map(v => {
             let obj = {}
             obj.username = v.用户名
             obj.num = v.学号
             arr.push(obj)
        })
        _this.tableData = [...arr];
        console.log( _this.tableData) */
      };
			  reader.readAsBinaryString(file)
    },
    getList (result) {
      // excel 数据再处理
      console.log(result)
      // result = result.slice(0,-1);
      // console.log(result)
      result.forEach((element, index, list) => {
        var obj = {
          'level_1': '',
          'level_2': '',
          'name': '',
          'idnumber': '',
          'sex': '',
          'nation': '',
          'birth': '',
          'edu': '',
          'degree': '',
          'politics': '',
          'preoccupation': '',
          'majoroccupation': '',
          'majortime': '',
          // 'sch': '',
          'jobrank': '',
          'address': '',
          'postalcode': '',
          'office': '',
          'phone': '',
          'qq': '',
          'fax': '',
          'email': ''
        }
        var newBirth = ''
        for (var key in this.prop) {
          console.log(element[this.prop['birth']])
          if (element[this.prop['idnumber']] === undefined) {
            break
          }
          obj[key] = element[this.prop[key]]
          console.log(element[this.prop['birth']] * 24 * 3600)
          // let timeChuo = element[this.prop['birth']] * 24 * 3600 * 1000
          // newBirth = moment(timeChuo).format('YYYY-MM-DD')
          // console.log(this.userInfo.sch)
        }
        // console.log(newBirth)
        // obj['sch_name'] = Lockr.get('schInfo')['sch_id_' + this.userInfo.sch]['sch_name']
        obj['sch'] = this.userInfo.sch
        // obj['birth'] = newBirth
        this.tableData.push(obj)
      })
      // console.log(this.tableData)
    }
    // timestampToTime (numb) {
    //   // 计算年月日时分的函数
    //   let format = '-'
    //   if (numb != undefined) {
    //     let time = new Date((numb - 1) * 24 * 3600000 + 1)
    //     time.setYear(time.getFullYear() - 70)
    //     let year = time.getFullYear() + ''
    //     let month = time.getMonth() + 1 + ''
    //     let date = time.getDate() + ''
    //     if (format && format.length === 1) {
    //       return year + format + month + format + date
    //     }
    //     return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    //   } else {
    //     return undefined
    //   }
    // }
  },
  computed: {
  },
  mounted() {
  },
  components: {
  },
  mixins:[http]
}

</script>
<style>
.box {
  position: relative;
  border-radius: 3px;
  background: #fff;
  border-top: 3px solid #d2d6de;
  margin-bottom: 20px;
  width: 100%;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  border-top-color: #3c8dbc;
}
.box-header {
  height: 34px;
  line-height: 34px;
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
}
.box-title {
  font-weight: 700;
  letter-spacing: 3px;
  display: inline-block;
  font-size: 18px;
  margin: 0;
}
.box-body {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
  padding: 10px;
  min-height: 0.01%;
  overflow-x: auto;
}
</style>
